package com.googlecode.framework.core.json.jackson;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;

import com.googlecode.framework.core.json.JsonMapper;
import com.googlecode.framework.core.json.JsonMappingException;

public class JacksonJsonMapper implements JsonMapper {

    private ObjectMapper om;
    
    public JacksonJsonMapper() {
        this(new ObjectMapper());
    }
    
    public JacksonJsonMapper(ObjectMapper om) {
        this.om = om;
    }
    
    @Override
    public <T> T fromJson(String content, Class<T> clazz) throws JsonMappingException {
        try {
            return om.readValue(content, clazz);
        } catch (JsonParseException e) {
            throw new JsonMappingException("json parse error.", e);
        } catch (org.codehaus.jackson.map.JsonMappingException e) {
            throw new JsonMappingException("json mapping error.", e);
        } catch (IOException e) {
            throw new JsonMappingException("json io error.", e);
        }
    }

    @Override
    public <T> T fromJson(Reader content, Class<T> clazz) throws JsonMappingException {
        try {
            return om.readValue(content, clazz);
        } catch (JsonParseException e) {
            throw new JsonMappingException("json parse error.", e);
        } catch (org.codehaus.jackson.map.JsonMappingException e) {
            throw new JsonMappingException("json mapping error.", e);
        } catch (IOException e) {
            throw new JsonMappingException("json io error.", e);
        }
    }

    @Override
    public String toJson(Object value) throws JsonMappingException {
        try {
            return om.writeValueAsString(value);
        } catch (JsonParseException e) {
            throw new JsonMappingException("json parse error.", e);
        } catch (org.codehaus.jackson.map.JsonMappingException e) {
            throw new JsonMappingException("json mapping error.", e);
        } catch (IOException e) {
            throw new JsonMappingException("json io error.", e);
        }
    }

    @Override
    public void toJson(Object value, Writer writer) throws JsonMappingException {
        try {
            om.writeValue(writer, value);
        } catch (JsonParseException e) {
            throw new JsonMappingException("json parse error.", e);
        } catch (org.codehaus.jackson.map.JsonMappingException e) {
            throw new JsonMappingException("json mapping error.", e);
        } catch (IOException e) {
            throw new JsonMappingException("json io error.", e);
        }    
    }

}
